package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    WeChatProperties weChatProperties;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User wxLogin(UserLoginDTO userLoginDTO) {

       String OpenId=   getOpenID(userLoginDTO.getCode());

       if (StringUtils.isEmpty(OpenId)){
           throw new UserNotLoginException(MessageConstant.LOGIN_FAILED);
       }

//通过openId查询用户
       User user= userMapper.getUserByOpenId(OpenId);


//       如果user不存在，表名是新用户，需要插入一条数据
        if (user==null){

            user=new User();

            user.setOpenid(OpenId);
            user.setCreateTime(LocalDateTime.now());

            userMapper.insertUser(user);

        }


        return user;
    }


    /**
     *  根据授权码 返回OpenId
     *
     * @param code
     * @return
     */
    private String getOpenID(String code) {
        HashMap<String, String> map = new HashMap<>();

        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);

//        s是一个json字符串，我们要获得其中的openid

        JSONObject parse = (JSONObject) JSON.parse(s);
        String openid = parse.get("openid").toString();
        log.info("openid:{}",openid);


        return openid;
    }
}
